﻿using Dapper;
using EFCore.Models;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using SIService;


namespace SService
{
    public class MenuService : IMenuService
    {
        // 从配置文件中获取数据库连接字符串
        private string ConnectionString = AppSettingsJson.Configuration.GetConnectionString("Conn");
        public async Task<List<Menu>> GetMenus(int uid)
        {
            using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
            {
                // 构建 SQL 查询语句
                string sql = $"SELECT P_PName,P_PNum,P_ParentNum,P_PUrl,P_PIcon FROM user_permissions_view WHERE U_UId = {uid} and P_PIsDelete=0;";
                // 从数据库中异步查询菜单信息
                List<Menu> menus = (await sqlConnection.QueryAsync<Menu>(sql)).ToList();
                // 调用私有方法获取菜单的子菜单并返回结果
                List<Menu> menu = await GetSecondaryMenus(menus, "000");
                return menu;
            }
        }

        // 递归获取菜单的子菜单信息
        private async Task<List<Menu>> GetSecondaryMenus(List<Menu> list, string parentNum)
        {
            List<Menu> menus = new List<Menu>();
            // 根据父菜单编号筛选菜单信息
            List<Menu> menu = list.Where(e => e.P_ParentNum == parentNum).ToList();
            foreach (Menu item in menu)
            {
                // 创建子菜单对象并递归获取子菜单的子菜单信息
                Menu menu1 = new Menu()
                {
                    P_PName = item.P_PName,
                    P_PNum = item.P_PNum,
                    P_ParentNum = item.P_ParentNum,
                    P_PUrl = item.P_PUrl,
                    P_PIcon = item.P_PIcon,
                    children = await GetSecondaryMenus(list, item.P_PNum)
                };
                // 将子菜单添加到菜单列表中
                menus.Add(menu1);
            }
            // 返回菜单列表
            return menus;
        }

    }
}
